//
//  HomeTableViewController.swift
//  微博－01
//
//  Created by 程雷 on 15/6/23.
//  Copyright (c) 2015年 程雷. All rights reserved.
//

import UIKit
import SVProgressHUD

let HomeTitleButtonClickNotification = "HomeTitleButtonClickNotification"

class HomeTableViewController: BaseTableViewController,StatusCellDelegate {

///  表格绑定的微博数据数组
    var statusesList:[Status]? {
        didSet{
            //刷新表格
            tableView.reloadData()

        }
    }
   
    // 定义行高缓存 ［statusId: 行高］
    lazy var rowHeightCache = [Int:CGFloat]()
    override func viewDidLoad() {
        super.viewDidLoad()

        visitorview?.setupViewInfo("visitordiscover_feed_image_house", message: "关注一些人，回这里看看有什么惊喜", isHome: true)
        
        //如果用户没有登录 直接返回
        if !userLogin
        {
            return
        }
        //以下代码都是登录之后才能执行的
        setupNavigationBar()
        // 加载数据
        prepareTableView()
        prepareRefresh()
        
        //注册通知,改变箭头图像
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "switchTitleButtonImage", name: HomeTitleButtonClickNotification, object: nil)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // 清空缓存 ,NSCache 不能清空
        rowHeightCache.removeAll()
    }
    
    //加载微博数据
    func loadData()
    {
        // 开始刷新 －不会触发监听方法 会显示刷新控件
        refreshControl?.beginRefreshing()
        
        //下拉刷新的代号 取到 数组中 第一条数据的 id
        var since_id = statusesList?.first?.id ?? 0
        
        // 上拉刷新，取到数组中最后一条数据 的 id
        var max_id = 0
        if pullRefreshFlag {
            since_id = 0
            
            max_id = statusesList?.last?.id ?? 0
        }
        Status.loadStatus(since_id, max_id: max_id) { (statuses,error) -> () in
            
            
            //关闭刷新按钮
            self.refreshControl?.endRefreshing()
            
            if error != nil {
                
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
                return
            }
            
            if statuses == nil
            {
                print("没有数据")
                return
            }
            
            //跟踪转发微博
            print("加载了\(statuses?.count)条微博")
            //判断是否有下啦刷新，将新的数据添加到原有数组的前面
            if since_id>0
            {
                self.statusesList = statuses! + self.statusesList!
            }
            else if max_id>0
            {
                //上啦刷新
                self.statusesList = self.statusesList! + statuses!
                self.pullRefreshFlag = false
            }
            else
            {
                // 初始刷新
                self.statusesList = statuses
            }
            
        }
    }

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        //开启动画
        visitorview?.startAnimation()
    }
    
    //MARK ---表格的数据源方法
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return statusesList?.count ?? 0
    }
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        // 1.取得数据模型
        let status = statusesList![indexPath.row]
        // 2.取标示符
        let ID = StatusCell.cellIdentifier(status)
        
        
        // 此方法必须要注册可重用 cell 如果不注册，就会崩溃
        let cell = tableView.dequeueReusableCellWithIdentifier(ID, forIndexPath: indexPath) as! StatusCell
        
        cell.photoDelegate = self
        
        //设置cell
        cell.status = status
        
        // 判断是否是最后一行
        if indexPath.row == statusesList!.count - 1
        {
            pullRefreshFlag = true
            loadData()
        }
        
        return cell
    }
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        // 1.取到对象
        let status = statusesList![indexPath.row]
        // 1.1判断是否缓存了行高，如果有直接返回
        if rowHeightCache[status.id] != nil
        {
            //返回行高
          //  print("返回行高缓存。。。")
            return rowHeightCache[status.id]!
        }
        
        // 2.获取 cell 从可重用的 缓冲池中抽取一个cell 要准确计算一个行高，需要实例化一个 cell
        // 2.1 可重用 id
        let ID = StatusCell.cellIdentifier(status)
        // 2.2 定义一个 类 默认是原创微博的 cell
        var cls:AnyClass = StatusNormalCell.self
        // 2.3 根据 id 判断时否是转发微博
        if ID == CLStatusForwardCellIndetifier
        {
            cls = StatusForwardCell.self
        }
        // 2.4 根据 cls 创建cell
        let cell = cls.new() as! StatusCell

        // 3.返回行高
        let height = cell.rowHeight(status)
        rowHeightCache[status.id] = height
        return height
    }
    //MARK ---cell 的代理方法
    func statusCellDidSelectedPhoto(cell: StatusCell, photoIndex: Int) {
        if cell.status?.largePicURLs == nil
        {
            return
        }
        // 传递数据 －－－图像数组 和拥护选中的图片
        let vc = PhotoBrowserViewController(urls: cell.status!.largePicURLs!, index: photoIndex)
        // 0.设置转场的素材
        presentedImageView.sd_setImageWithURL(cell.status!.largePicURLs![photoIndex])
        presentedImageView.frame = cell.screenFrame(photoIndex)
        presentedImageView.contentMode = UIViewContentMode.ScaleAspectFill
        // 目标位置
        presentedFrame = cell.fullScreenFrame(photoIndex)
        // 记录当前行
        selectedStatusCell = cell
        // 1.设置转场代理
        vc.transitioningDelegate = self
        // 2.设置转场的模式
        vc.modalPresentationStyle = UIModalPresentationStyle.Custom
        
        presentViewController(vc, animated: true, completion: nil)
    }
    // 1.临时的图片视图
    private lazy var  presentedImageView = UIImageView()
    // 2. 目标位置
    private lazy var  presentedFrame = CGRectZero
    // 3. 拥护选中照片的表格行
    private var selectedStatusCell:StatusCell?
    
    // 显示二维码
    func showQRCode()
    {
        let sb = UIStoryboard(name: "QRCode", bundle: nil)
        presentViewController(sb.instantiateInitialViewController()!, animated: true,completion: nil)

        
    }
    //动画转场代理
    let popoverAnimator = PopoverAnimator()
    
    func titleButtonClicked() {
        
        // 改变图片状态
        let sb = UIStoryboard(name: "FriendGroup", bundle: nil)
        let vc = sb.instantiateViewControllerWithIdentifier("FriendGroupSB")
        
        // 1.设置转场代理
        vc.transitioningDelegate = popoverAnimator
        // 2.设置展现视图的大小
        let x = (view.bounds.width-200)*0.5
        popoverAnimator.presentFrame = CGRectMake(x, 56, 180, 260)
        // 2.设置转场的动画
        vc.modalPresentationStyle = UIModalPresentationStyle.Custom
        
        presentViewController(vc, animated: true, completion: nil)
        // 调用改变图片函数
        switchTitleButtonImage()
    }
    // 改变
    var switchImage:Bool = true
    //全局的 变量
    var titleButton = homeTitleButton()
    
    //改变图片 NavigationBartitleButtond的图片
    func switchTitleButtonImage()
    {
        switchImage = !switchImage
        let imageName = switchImage ? "navigationbar_arrow_down" :"navigationbar_arrow_up"
        titleButton.setImage(UIImage(named: imageName), forState: UIControlState.Normal)
        
    }
///  设置导航条
    private func setupNavigationBar()
    {
        //判断用户是否登录
        if sharedUserAccount == nil
        {
            //表示没有登录
            return
        }
        //设置按钮

        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendsearch", highlightedImageName: nil)
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", highlightedImageName: nil)
        
        print(navigationItem.rightBarButtonItem!.customView)
        
        // 1.1 获取button
        let btn = navigationItem.rightBarButtonItem!.customView as! UIButton
        
        // 1.2 获取 target
        
        btn.addTarget(self, action: "showQRCode", forControlEvents: UIControlEvents.TouchUpInside)
        //设置标题
        
        titleButton = homeTitleButton.button(sharedUserAccount!.name!)
        
        titleButton.addTarget(self, action: "titleButtonClicked", forControlEvents: UIControlEvents.TouchUpInside)
        
        navigationItem.titleView = titleButton
    }
    
///  准备 tableView
    private func prepareTableView() {
        
        // 注册可重用的cell
        tableView.registerClass(StatusForwardCell.self, forCellReuseIdentifier: CLStatusForwardCellIndetifier)
        tableView.registerClass(StatusNormalCell.self , forCellReuseIdentifier: CLStatusNormalCellIndetifier)
        
        // 设置行高 - 如果使用缓存行高（自己计算高度），不能使用预估高度
        // 取消分割线
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
    }
    
    // 准备刷新控件
    private func prepareRefresh() {
        
        refreshControl = CLRefreshControl()
        // 添加监听方法
        refreshControl?.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
        // 加载数据
        loadData()

    }
    //上拉刷新标记
    private var pullRefreshFlag = false
    private var isPresented = false
}

extension HomeTableViewController:UIViewControllerTransitioningDelegate,UIViewControllerAnimatedTransitioning{
    // 返回提供 转场 modal 动画的对象
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresented = true
        
        return self
    }
    // 返回提供转场 dismiss 动画对象
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresented = false
        return self
    }
    
    func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
        return 0.5
    }
    
    // 一旦实现，需要程序员提供动画
    func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
        // 1. 获取目标视图
        let viewKey = isPresented ? UITransitionContextToViewKey : UITransitionContextFromViewKey
        let targetView = transitionContext.viewForKey(viewKey)
        if targetView == nil
        {
            return
        }
        
        if isPresented
        {
            // 2.添加 toView
            transitionContext.containerView()?.addSubview(targetView!)
            targetView?.alpha = 0
            
            // 2.1 添加临时的图片视图
            transitionContext.containerView()?.addSubview(presentedImageView)
            
            // 3.动画
            UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
               
                self.presentedImageView.frame = self.presentedFrame
                
                }, completion: { (_) -> Void in
                    
                    self.presentedImageView.removeFromSuperview()
                    targetView?.alpha = 1
                    // 告诉动画完成
                    transitionContext.completeTransition(true)
            })
        }
        else
        {
            // 0 获取要缩放的照片
            let targetVc = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as! PhotoBrowserViewController
            let iv = targetVc.currentImageView()
            iv.contentMode = UIViewContentMode.ScaleAspectFill
            //叠加形变
            iv.transform = CGAffineTransformScale(iv.transform, targetView!.transform.a, targetView!.transform.a)
            
            // 设置图像视图的中心点
            iv.center = targetView!.center
            
            // 1.添加容器到视图
            transitionContext.containerView()?.addSubview(iv)
            // 2.将目标视图直接删除
            targetView?.removeFromSuperview()
            // 3.恢复的位置
            let targetFrame = selectedStatusCell!.screenFrame(targetVc.currentImageIndex())
            
            // 动画
            UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
                iv.frame = targetFrame
                }, completion: { (_) -> Void in
                    iv.removeFromSuperview()
                    transitionContext.completeTransition(true)
            })
        }
    }
}

